<?php

class Student_ImportDataController extends Zend_Controller_Action
{
    protected $_cYear;
    protected $_default_student_id_prefix_numbers;
    public function init()
    {
        // 取系統預設值
        $param = new Default_Model_ModulesParam();
        $param_arr = $param->getParamByResourceId('student');
        // 前置位元數
        $this->_cYear = substr($this->view->Semester['year'], -$param_arr['default_student_id_prefix_numbers']);
        $this->_default_student_id_prefix_numbers = $param_arr['default_student_id_prefix_numbers'];
    }

    public function indexAction()
    {


        $form = new Student_Form_Import();

        $label =  $form->getElement('currentSemester')->getLabel().','.
        sprintf($this->view->translate('student id prefix %d'),$this->_cYear);
        $form->getElement('currentSemester')->setLabel($label);
        $request = $this->getRequest();
        if ($request->isPost()){
            if ($form->isValid($request->getPost())) {
                // 比對欄位順是否正確
                $locale = Bootstrap::$config['resources']['locale']['default'];
                $serverCsv = new Sfs_Csv(dirname(__FILE__).'/../languages/'.$locale.'/studentDemo.csv');
                $clientCsv = new Sfs_Csv($_FILES['studentCsv']['tmp_name']);
                $titleArr = $serverCsv->current() ;
                if ($titleArr == $clientCsv->current()) {
                    $this->view->titleArr = $titleArr;
                    $data = array();
                    while($clientCsv->next())
                    if ($temp = $clientCsv->current())
                    $data[] = $temp;
                    // 檢查資料的正確性
                    if ($this->_checkData(&$data)){
                        $semesterClass = new Semester_Model_SemesterClass();
                        $classArr = $semesterClass->getClassSetName($this->view->Semester['year'],
                        $this->view->Semester['semester']);
                        foreach($data as $row) {
                            $cYear = $this->view->Semester['year']-$row[3]+$this->view->lowYear;
                            $student = new Student_Model_Student();
                            $student->name = $row[1];
                            if ($row[2]==1)
                            $student->sex = 'M';
                            else
                            $student->sex = 'F';
                            $student->birthday = $row[6];
                            $student->identification_number = $row[7];
                            $student->address_zip= $row[8];
                            $student->phone_registered = $row[11];
                            $student->phone_mobile = $row[11];
                            if ($this->view->lowYear == 1 ) //國小
                            $student->preschool_name = $row[14];
                            else
                            $student->elementary_school_name = $row[14];

                            $student->registered_address = $row[12];
                            $student->address = $row[12];

                            // 地址拆解
                            $addressArr = $student->splitAddress($row[12]);
                            if ($addressArr) {
                                $student->registered_county = $addressArr[0];
                                $student->registered_town = $addressArr[1];
                                $student->registered_village = $addressArr[2];
                                $student->registered_neighbor = $addressArr[3];
                                $student->registered_road = $addressArr[4];
                                $student->registered_section = $addressArr[5];
                                $student->registered_lane = $addressArr[6];
                                $student->registered_alley = $addressArr[7];
                                $student->registered_no = $addressArr[8];
                                $student->registered_extend = $addressArr[9];
                                $student->registered_floor = $addressArr[10];
                                $student->registered_floor_extend = $addressArr[11];
                            }
                            //覆蓋舊資料
                            if ($this->_getParam('noReplace') != 1 and isset($row['student_sn'])) {
                                $student->assignIdentifier($row['student_sn']);
                                $sn = $row['student_sn'];
                                $student->save();
                            }
                            else {
                                $student->save();
                                $sn = $student->sn;
                            }

                            // 學生學期資料
                            $studentSemester = new Student_Model_StudentSemester();
                            $studentSemester->year = $this->view->Semester['year'];
                            $studentSemester->semester = $this->view->Semester['semester'];
                            $studentSemester->student_sn = $sn;
                            $studentSemester->grade = $cYear;
                            $studentSemester->class_sn = $row[4];
                            $studentSemester->class = $classArr[$row[4]] ;
                            $studentSemester->number = $row[5];
                            $studentSemester->student_id = $row[0];
                            if ($this->_getParam('noReplace') != 1 ) {
                                $q = Doctrine_Query::create()
                                ->select('sn')
                                ->from('Student_Model_StudentSemester')
                                ->where('year=?', $this->view->Semester['year'])
                                ->andWhere('semester=?', $this->view->Semester['semester'])
                                ->andWhere('student_sn=?', $sn)
                                ->andWhere('grade=?', $cYear)
                                ->fetchOne();
                                if ($q)
                                $studentSemester->assignIdentifier($q->sn);
                            }
                            $studentSemester->save();

                            if ($this->_getParam('noReplace') != 1 ) {
                                // 先刪除舊資料
                                Doctrine_Query::create()
                                ->delete('Student_Model_StudentParents')
                                ->where('student_sn=?', $sn)
                                ->execute();
                                  Doctrine_Query::create()
                                ->delete('Student_Model_StudentCharacter')
                                ->where('student_sn=?', $sn)
                                ->execute();
                              }
                            // 父母親資料
                            $studentParent = new Student_Model_StudentParents();
                            $studentParent->student_sn = $sn;
                            $studentParent->name = $row[8];
                            $studentParent->sex = 'M';
                            $studentParent->replace();

                            $studentParent = new Student_Model_StudentParents();
                            $studentParent->student_sn = $sn;
                            $studentParent->name = $row[9];
                            $studentParent->sex = 'F';
                            $studentParent->replace();

                            // 學生身分別
                            $studentCharacter = new Student_Model_StudentCharacter();
                            $studentCharacter->student_sn = $sn;
                            $studentCharacter->kind = 0;
                            $studentCharacter->replace();
                        }

                        $this->view->okData = $data;
                    }
                }
                else
                $this->view->errorMessage = 'error item title' ;
            }
        }


        $this->view->form = $form;
    }

    /**
     * 檢查資料的正確性
     * @param array $data
     */
    protected function _checkData($data)
    {
        $error = array();
        $studentIdArray = $numberArray = $personIdArray = array();

        $i =0;
        foreach ($data as $row) {
            // 學號
            if ($row[0]=='')
            $error[$i][0] = 'empty';
            elseif (in_array($row[0],$studentIdArray))
            $error[$i][0] = 'double';
            elseif ($this->_getParam('currentSemester')) {
                if (substr($row[0],0,$this->_default_student_id_prefix_numbers) != $this->view->Semester['year'])
                $error[$i][0] = 'year not match';
            }
            else
            $studentIdArray[] = $row[0];

            // 姓名
            if ($row[1]=='')
            $error[$i][1] = 'empty';

            // 性別
            if ($row[2] != 1 && $row[2] !=2)
            $error[$i][2] = 'not_match';

            // 檢查年級班級
            $cYear = $this->view->Semester['year']-$row[3]+$this->view->lowYear;
            $q = Doctrine_Query::create()
            ->from('Semester_Model_SemesterClass a')
            ->where('a.year=?', $this->view->Semester['year'])
            ->andWhere('a.semester=?', $this->view->Semester['semester'])
            ->andWhere('a.grade=?', $cYear)
            ->andWhere('a.class_sn=?', $row[4]);
            $res = $q->fetchArray();
            if (count($res) == 0)
            $error[$i][4] = 'class_data_yet_assigned';


            // 座號
            if ($row[5]=='')
            $error[$i][5] = 'empty';
            elseif (in_array($row[5],$numberArray))
            $error[$i][5] = 'double';
            else
            $numberArray[] = $row[5];

            // 身分證號
            if ($row[7] == '')
            $error[$i][7] = 'empty';
            elseif (in_array($row[7],$personIdArray))
            $error[$i][7] = 'double';
            else
            $personIdArray[] = $row[7];

            $q = Doctrine_Query::create()
            ->select('a.sn, b.student_id')
            ->from('Student_Model_Student a')
            ->leftJoin('a.Student_Model_StudentSemester b')
            ->where('a.study_condition=?', 0)
            ->andwhere('b.student_id=?', $row[0])
            ->andWhere('a.identification_number=?', $row[7]);
            $res = $q->fetchOne();
            if ($res) {
                // 檢查在籍生是否有相同的身分證號
                if ($this->_getParam('noReplace') == 1)
                $error[$i][7] = 'double_old';
                // 記錄學生sn
                $data[$i]['student_sn'] = $res->sn;
            }
            //檢查生日
            $stud_birthday_array=split("[/.-]",$row[6]);
            if($stud_birthday_array[0] <1900 || $stud_birthday_array[0]>2030
            || $stud_birthday_array[1]<1 || $stud_birthday_array[1]>12 ||
            $stud_birthday_array[2]<1 || $stud_birthday_array[2]>31)
            $error[$i][6] = 'not_match';

            $i++ ;
        }

        if ($error) {
            $this->view->oldData = $data;
            $this->view->error = $error;
            return false;
        }
        else
        return true;
    }

    public function demoAction()
    {
        $locale = Bootstrap::$config['resources']['locale']['default'];
        $path = dirname(__FILE__).'/../languages/'.$locale.'/studentDemo.csv';
        $this->_helper->SendFile($path, 'text/csv');
    }

}

